package com.mysite.websocket.controller;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mysite.websocket.vo.FileVo;

@Controller
@RequestMapping("/file")
public class FileController extends BaseController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upload(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "_file", required = false) MultipartFile[] fileArray) throws Exception {
        List<FileVo> files = new ArrayList<FileVo>();
        if (fileArray != null && fileArray.length > 0) {
            for (MultipartFile file : fileArray) {
                System.out.println("表单名称: " + file.getName());
                System.out.println("文件名称: " + file.getOriginalFilename());
                InputStream is = file.getInputStream();
                String fileName = file.getOriginalFilename();
                OutputStream os = new FileOutputStream(storageFilePath + fileName);
                IOUtils.copy(is, os);
                is.close();
                os.flush();
                os.close();

                FileVo vo = new FileVo();
                vo.setName(file.getOriginalFilename());
                vo.setPath(storageFilePath + fileName);
                files.add(vo);
            }
        }

        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (files.isEmpty()) {
            resultMap.put("uploaded", false);
        } else {
            resultMap.put("uploaded", true);
            resultMap.put("files", files);
        }
        return resultMap;
    }
    
    @RequestMapping(value = "/upload/success")
    @ResponseBody
    public String uploadSuccess(String data) throws Exception {
        return data;
    }
}
